<?php

declare(strict_types=1);

namespace App\Utils;

use AlibabaCloud\SDK\Dyvmsapi\V20170525\Dyvmsapi;
use AlibabaCloud\SDK\Dyvmsapi\V20170525\Models\SingleCallByTtsRequest;
use AlibabaCloud\SDK\Dyvmsapi\V20170525\Models\SingleCallByVoiceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

use Throwable;

use function Hyperf\Config\config;

class AliyunDyvmsapi
{
    private Dyvmsapi $client;

    public function __construct()
    {
        $config = new Config([
            'accessKeyId' => config('aliyun.dyvmsapi.access_key_id'),
            'accessKeySecret' => config('aliyun.dyvmsapi.access_key_secret'),
        ]);
        $config->endpoint = config('aliyun.dyvmsapi.endpoint');
        $this->client = new Dyvmsapi($config);
    }

    /**
     * 向指定号码发送语音通知文件类型的语音通知
     * 单用户调用频率：1200 次/秒。
     * @link https://help.aliyun.com/zh/vms/developer-reference/api-dyvmsapi-2017-05-25-singlecallbyvoice
     * @param string $phone
     * @param string $code
     * @return void
     */
    public function singleCallByVoice(string $phone, string $code): void
    {
        try {
            $singleCallByVoiceRequest = new SingleCallByVoiceRequest([
                'calledNumber' => $phone,
                'voiceCode' => $code,
            ]);
            $runtime = new RuntimeOptions([
                'connectTimeout' => 5000,
            ]);
            $this->client->singleCallByVoiceWithOptions($singleCallByVoiceRequest, $runtime);
        } catch (Throwable $e) {
            business_error_logger(__FUNCTION__, $e);
        }
    }

    /**
     * 向指定号码发送语音验证码或文本转语音类型的语音通知
     * 单用户调用频率：1000 次/秒。
     * @link https://help.aliyun.com/zh/vms/developer-reference/api-dyvmsapi-2017-05-25-singlecallbytts
     * @param string $phone
     * @param string $code
     * @return void
     */
    public function singleCallByTts(string $phone, string $code): void
    {
        try {
            $singleCallByTtsRequest = new SingleCallByTtsRequest([
                'calledNumber' => $phone,
                'ttsCode' => $code,
            ]);
            $runtime = new RuntimeOptions([
                'connectTimeout' => 5000,
            ]);
            $this->client->singleCallByTtsWithOptions($singleCallByTtsRequest, $runtime);
        } catch (Throwable $e) {
            business_error_logger(__FUNCTION__, $e);
        }
    }
}
